/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.hcbank.jpa.controllers;

import com.hcbank.jpa.controllers.exceptions.IllegalOrphanException;
import com.hcbank.jpa.controllers.exceptions.NonexistentEntityException;
import com.hcbank.jpa.controllers.exceptions.PreexistingEntityException;
import com.hcbank.jpa.controllers.exceptions.RollbackFailureException;
import com.hcbank.jpa.entities.AccountEntity;
import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import com.hcbank.jpa.entities.CustomerEntity;
import com.hcbank.jpa.entities.AccountHistoryEntity;
import java.util.ArrayList;
import java.util.List;
import com.hcbank.jpa.entities.TransactionEntity;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.transaction.UserTransaction;

/**
 *
 * @author NHAHV
 */
public class AccountEntityJpaController implements Serializable {

    public AccountEntityJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(AccountEntity accountEntity) throws PreexistingEntityException, RollbackFailureException, Exception {
        if (accountEntity.getAccountHistoryEntityList() == null) {
            accountEntity.setAccountHistoryEntityList(new ArrayList<AccountHistoryEntity>());
        }
        if (accountEntity.getTransactionEntityList() == null) {
            accountEntity.setTransactionEntityList(new ArrayList<TransactionEntity>());
        }
        if (accountEntity.getTransactionEntityList1() == null) {
            accountEntity.setTransactionEntityList1(new ArrayList<TransactionEntity>());
        }
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            CustomerEntity customerId = accountEntity.getCustomerId();
            if (customerId != null) {
                customerId = em.getReference(customerId.getClass(), customerId.getId());
                accountEntity.setCustomerId(customerId);
            }
            List<AccountHistoryEntity> attachedAccountHistoryEntityList = new ArrayList<AccountHistoryEntity>();
            for (AccountHistoryEntity accountHistoryEntityListAccountHistoryEntityToAttach : accountEntity.getAccountHistoryEntityList()) {
                accountHistoryEntityListAccountHistoryEntityToAttach = em.getReference(accountHistoryEntityListAccountHistoryEntityToAttach.getClass(), accountHistoryEntityListAccountHistoryEntityToAttach.getId());
                attachedAccountHistoryEntityList.add(accountHistoryEntityListAccountHistoryEntityToAttach);
            }
            accountEntity.setAccountHistoryEntityList(attachedAccountHistoryEntityList);
            List<TransactionEntity> attachedTransactionEntityList = new ArrayList<TransactionEntity>();
            for (TransactionEntity transactionEntityListTransactionEntityToAttach : accountEntity.getTransactionEntityList()) {
                transactionEntityListTransactionEntityToAttach = em.getReference(transactionEntityListTransactionEntityToAttach.getClass(), transactionEntityListTransactionEntityToAttach.getId());
                attachedTransactionEntityList.add(transactionEntityListTransactionEntityToAttach);
            }
            accountEntity.setTransactionEntityList(attachedTransactionEntityList);
            List<TransactionEntity> attachedTransactionEntityList1 = new ArrayList<TransactionEntity>();
            for (TransactionEntity transactionEntityList1TransactionEntityToAttach : accountEntity.getTransactionEntityList1()) {
                transactionEntityList1TransactionEntityToAttach = em.getReference(transactionEntityList1TransactionEntityToAttach.getClass(), transactionEntityList1TransactionEntityToAttach.getId());
                attachedTransactionEntityList1.add(transactionEntityList1TransactionEntityToAttach);
            }
            accountEntity.setTransactionEntityList1(attachedTransactionEntityList1);
            em.persist(accountEntity);
            if (customerId != null) {
                customerId.getAccountEntityList().add(accountEntity);
                customerId = em.merge(customerId);
            }
            for (AccountHistoryEntity accountHistoryEntityListAccountHistoryEntity : accountEntity.getAccountHistoryEntityList()) {
                AccountEntity oldAccountIdOfAccountHistoryEntityListAccountHistoryEntity = accountHistoryEntityListAccountHistoryEntity.getAccountId();
                accountHistoryEntityListAccountHistoryEntity.setAccountId(accountEntity);
                accountHistoryEntityListAccountHistoryEntity = em.merge(accountHistoryEntityListAccountHistoryEntity);
                if (oldAccountIdOfAccountHistoryEntityListAccountHistoryEntity != null) {
                    oldAccountIdOfAccountHistoryEntityListAccountHistoryEntity.getAccountHistoryEntityList().remove(accountHistoryEntityListAccountHistoryEntity);
                    oldAccountIdOfAccountHistoryEntityListAccountHistoryEntity = em.merge(oldAccountIdOfAccountHistoryEntityListAccountHistoryEntity);
                }
            }
            for (TransactionEntity transactionEntityListTransactionEntity : accountEntity.getTransactionEntityList()) {
                AccountEntity oldToAccountOfTransactionEntityListTransactionEntity = transactionEntityListTransactionEntity.getToAccount();
                transactionEntityListTransactionEntity.setToAccount(accountEntity);
                transactionEntityListTransactionEntity = em.merge(transactionEntityListTransactionEntity);
                if (oldToAccountOfTransactionEntityListTransactionEntity != null) {
                    oldToAccountOfTransactionEntityListTransactionEntity.getTransactionEntityList().remove(transactionEntityListTransactionEntity);
                    oldToAccountOfTransactionEntityListTransactionEntity = em.merge(oldToAccountOfTransactionEntityListTransactionEntity);
                }
            }
            for (TransactionEntity transactionEntityList1TransactionEntity : accountEntity.getTransactionEntityList1()) {
                AccountEntity oldFromAccountOfTransactionEntityList1TransactionEntity = transactionEntityList1TransactionEntity.getFromAccount();
                transactionEntityList1TransactionEntity.setFromAccount(accountEntity);
                transactionEntityList1TransactionEntity = em.merge(transactionEntityList1TransactionEntity);
                if (oldFromAccountOfTransactionEntityList1TransactionEntity != null) {
                    oldFromAccountOfTransactionEntityList1TransactionEntity.getTransactionEntityList1().remove(transactionEntityList1TransactionEntity);
                    oldFromAccountOfTransactionEntityList1TransactionEntity = em.merge(oldFromAccountOfTransactionEntityList1TransactionEntity);
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            if (findAccountEntity(accountEntity.getId()) != null) {
                throw new PreexistingEntityException("AccountEntity " + accountEntity + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(AccountEntity accountEntity) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            AccountEntity persistentAccountEntity = em.find(AccountEntity.class, accountEntity.getId());
            CustomerEntity customerIdOld = persistentAccountEntity.getCustomerId();
            CustomerEntity customerIdNew = accountEntity.getCustomerId();
            List<AccountHistoryEntity> accountHistoryEntityListOld = persistentAccountEntity.getAccountHistoryEntityList();
            List<AccountHistoryEntity> accountHistoryEntityListNew = accountEntity.getAccountHistoryEntityList();
            List<TransactionEntity> transactionEntityListOld = persistentAccountEntity.getTransactionEntityList();
            List<TransactionEntity> transactionEntityListNew = accountEntity.getTransactionEntityList();
            List<TransactionEntity> transactionEntityList1Old = persistentAccountEntity.getTransactionEntityList1();
            List<TransactionEntity> transactionEntityList1New = accountEntity.getTransactionEntityList1();
            List<String> illegalOrphanMessages = null;
            for (AccountHistoryEntity accountHistoryEntityListOldAccountHistoryEntity : accountHistoryEntityListOld) {
                if (!accountHistoryEntityListNew.contains(accountHistoryEntityListOldAccountHistoryEntity)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain AccountHistoryEntity " + accountHistoryEntityListOldAccountHistoryEntity + " since its accountId field is not nullable.");
                }
            }
            for (TransactionEntity transactionEntityListOldTransactionEntity : transactionEntityListOld) {
                if (!transactionEntityListNew.contains(transactionEntityListOldTransactionEntity)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain TransactionEntity " + transactionEntityListOldTransactionEntity + " since its toAccount field is not nullable.");
                }
            }
            for (TransactionEntity transactionEntityList1OldTransactionEntity : transactionEntityList1Old) {
                if (!transactionEntityList1New.contains(transactionEntityList1OldTransactionEntity)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain TransactionEntity " + transactionEntityList1OldTransactionEntity + " since its fromAccount field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            if (customerIdNew != null) {
                customerIdNew = em.getReference(customerIdNew.getClass(), customerIdNew.getId());
                accountEntity.setCustomerId(customerIdNew);
            }
            List<AccountHistoryEntity> attachedAccountHistoryEntityListNew = new ArrayList<AccountHistoryEntity>();
            for (AccountHistoryEntity accountHistoryEntityListNewAccountHistoryEntityToAttach : accountHistoryEntityListNew) {
                accountHistoryEntityListNewAccountHistoryEntityToAttach = em.getReference(accountHistoryEntityListNewAccountHistoryEntityToAttach.getClass(), accountHistoryEntityListNewAccountHistoryEntityToAttach.getId());
                attachedAccountHistoryEntityListNew.add(accountHistoryEntityListNewAccountHistoryEntityToAttach);
            }
            accountHistoryEntityListNew = attachedAccountHistoryEntityListNew;
            accountEntity.setAccountHistoryEntityList(accountHistoryEntityListNew);
            List<TransactionEntity> attachedTransactionEntityListNew = new ArrayList<TransactionEntity>();
            for (TransactionEntity transactionEntityListNewTransactionEntityToAttach : transactionEntityListNew) {
                transactionEntityListNewTransactionEntityToAttach = em.getReference(transactionEntityListNewTransactionEntityToAttach.getClass(), transactionEntityListNewTransactionEntityToAttach.getId());
                attachedTransactionEntityListNew.add(transactionEntityListNewTransactionEntityToAttach);
            }
            transactionEntityListNew = attachedTransactionEntityListNew;
            accountEntity.setTransactionEntityList(transactionEntityListNew);
            List<TransactionEntity> attachedTransactionEntityList1New = new ArrayList<TransactionEntity>();
            for (TransactionEntity transactionEntityList1NewTransactionEntityToAttach : transactionEntityList1New) {
                transactionEntityList1NewTransactionEntityToAttach = em.getReference(transactionEntityList1NewTransactionEntityToAttach.getClass(), transactionEntityList1NewTransactionEntityToAttach.getId());
                attachedTransactionEntityList1New.add(transactionEntityList1NewTransactionEntityToAttach);
            }
            transactionEntityList1New = attachedTransactionEntityList1New;
            accountEntity.setTransactionEntityList1(transactionEntityList1New);
            accountEntity = em.merge(accountEntity);
            if (customerIdOld != null && !customerIdOld.equals(customerIdNew)) {
                customerIdOld.getAccountEntityList().remove(accountEntity);
                customerIdOld = em.merge(customerIdOld);
            }
            if (customerIdNew != null && !customerIdNew.equals(customerIdOld)) {
                customerIdNew.getAccountEntityList().add(accountEntity);
                customerIdNew = em.merge(customerIdNew);
            }
            for (AccountHistoryEntity accountHistoryEntityListNewAccountHistoryEntity : accountHistoryEntityListNew) {
                if (!accountHistoryEntityListOld.contains(accountHistoryEntityListNewAccountHistoryEntity)) {
                    AccountEntity oldAccountIdOfAccountHistoryEntityListNewAccountHistoryEntity = accountHistoryEntityListNewAccountHistoryEntity.getAccountId();
                    accountHistoryEntityListNewAccountHistoryEntity.setAccountId(accountEntity);
                    accountHistoryEntityListNewAccountHistoryEntity = em.merge(accountHistoryEntityListNewAccountHistoryEntity);
                    if (oldAccountIdOfAccountHistoryEntityListNewAccountHistoryEntity != null && !oldAccountIdOfAccountHistoryEntityListNewAccountHistoryEntity.equals(accountEntity)) {
                        oldAccountIdOfAccountHistoryEntityListNewAccountHistoryEntity.getAccountHistoryEntityList().remove(accountHistoryEntityListNewAccountHistoryEntity);
                        oldAccountIdOfAccountHistoryEntityListNewAccountHistoryEntity = em.merge(oldAccountIdOfAccountHistoryEntityListNewAccountHistoryEntity);
                    }
                }
            }
            for (TransactionEntity transactionEntityListNewTransactionEntity : transactionEntityListNew) {
                if (!transactionEntityListOld.contains(transactionEntityListNewTransactionEntity)) {
                    AccountEntity oldToAccountOfTransactionEntityListNewTransactionEntity = transactionEntityListNewTransactionEntity.getToAccount();
                    transactionEntityListNewTransactionEntity.setToAccount(accountEntity);
                    transactionEntityListNewTransactionEntity = em.merge(transactionEntityListNewTransactionEntity);
                    if (oldToAccountOfTransactionEntityListNewTransactionEntity != null && !oldToAccountOfTransactionEntityListNewTransactionEntity.equals(accountEntity)) {
                        oldToAccountOfTransactionEntityListNewTransactionEntity.getTransactionEntityList().remove(transactionEntityListNewTransactionEntity);
                        oldToAccountOfTransactionEntityListNewTransactionEntity = em.merge(oldToAccountOfTransactionEntityListNewTransactionEntity);
                    }
                }
            }
            for (TransactionEntity transactionEntityList1NewTransactionEntity : transactionEntityList1New) {
                if (!transactionEntityList1Old.contains(transactionEntityList1NewTransactionEntity)) {
                    AccountEntity oldFromAccountOfTransactionEntityList1NewTransactionEntity = transactionEntityList1NewTransactionEntity.getFromAccount();
                    transactionEntityList1NewTransactionEntity.setFromAccount(accountEntity);
                    transactionEntityList1NewTransactionEntity = em.merge(transactionEntityList1NewTransactionEntity);
                    if (oldFromAccountOfTransactionEntityList1NewTransactionEntity != null && !oldFromAccountOfTransactionEntityList1NewTransactionEntity.equals(accountEntity)) {
                        oldFromAccountOfTransactionEntityList1NewTransactionEntity.getTransactionEntityList1().remove(transactionEntityList1NewTransactionEntity);
                        oldFromAccountOfTransactionEntityList1NewTransactionEntity = em.merge(oldFromAccountOfTransactionEntityList1NewTransactionEntity);
                    }
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = accountEntity.getId();
                if (findAccountEntity(id) == null) {
                    throw new NonexistentEntityException("The accountEntity with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            AccountEntity accountEntity;
            try {
                accountEntity = em.getReference(AccountEntity.class, id);
                accountEntity.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The accountEntity with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            List<AccountHistoryEntity> accountHistoryEntityListOrphanCheck = accountEntity.getAccountHistoryEntityList();
            for (AccountHistoryEntity accountHistoryEntityListOrphanCheckAccountHistoryEntity : accountHistoryEntityListOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This AccountEntity (" + accountEntity + ") cannot be destroyed since the AccountHistoryEntity " + accountHistoryEntityListOrphanCheckAccountHistoryEntity + " in its accountHistoryEntityList field has a non-nullable accountId field.");
            }
            List<TransactionEntity> transactionEntityListOrphanCheck = accountEntity.getTransactionEntityList();
            for (TransactionEntity transactionEntityListOrphanCheckTransactionEntity : transactionEntityListOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This AccountEntity (" + accountEntity + ") cannot be destroyed since the TransactionEntity " + transactionEntityListOrphanCheckTransactionEntity + " in its transactionEntityList field has a non-nullable toAccount field.");
            }
            List<TransactionEntity> transactionEntityList1OrphanCheck = accountEntity.getTransactionEntityList1();
            for (TransactionEntity transactionEntityList1OrphanCheckTransactionEntity : transactionEntityList1OrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This AccountEntity (" + accountEntity + ") cannot be destroyed since the TransactionEntity " + transactionEntityList1OrphanCheckTransactionEntity + " in its transactionEntityList1 field has a non-nullable fromAccount field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            CustomerEntity customerId = accountEntity.getCustomerId();
            if (customerId != null) {
                customerId.getAccountEntityList().remove(accountEntity);
                customerId = em.merge(customerId);
            }
            em.remove(accountEntity);
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<AccountEntity> findAccountEntityEntities() {
        return findAccountEntityEntities(true, -1, -1);
    }

    public List<AccountEntity> findAccountEntityEntities(int maxResults, int firstResult) {
        return findAccountEntityEntities(false, maxResults, firstResult);
    }

    private List<AccountEntity> findAccountEntityEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(AccountEntity.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public AccountEntity findAccountEntity(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(AccountEntity.class, id);
        } finally {
            em.close();
        }
    }

    public int getAccountEntityCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<AccountEntity> rt = cq.from(AccountEntity.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
